/**
 * 作者: 会写BUG
 * 创作日期: 2025/3/27 22:31
 * 描述: cwbQtPractice.GameButton
 *
 *
 **/

#pragma once

#include "game_button.h"

#include <QPainter>
#include <QVariantAnimation>
#include <QMouseEvent>

GameButton::GameButton(QWidget *_parent) : QAbstractButton(_parent) {

}

GameButton::GameButton(const QString & _text, QWidget *_parent)
        : QAbstractButton(_parent){
    setText(_text);
}

GameButton::~GameButton() {

}

void GameButton::paintEvent(QPaintEvent *e) {
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
    painter.setPen(Qt::transparent);

    painter.setBrush(Qt::transparent);
    painter.drawRect(rect());

    QRect shadow_rect = QRect(rect()).adjusted(shadow_offset_, shadow_offset_,
        -shadow_offset_, -shadow_offset_);
    QRect button_rect = QRect(shadow_rect).adjusted(-offset_, -offset_,
        -offset_, -offset_);

    painter.setBrush(QColor(173, 133, 81));
    painter.drawRect(shadow_rect);

    painter.setBrush(QColor(229, 192, 148));
    painter.drawRect(button_rect);

    painter.setPen(Qt::white);
    painter.drawText(button_rect, Qt::AlignCenter, text());
}

void GameButton::mousePressEvent(QMouseEvent * _event) {
    if (_event->button() == Qt::LeftButton) {
        down();
    }
}

void GameButton::mouseReleaseEvent(QMouseEvent * _event) {
    if (_event->button() == Qt::LeftButton) {
        up();
    }
    Q_EMIT clicked();
}

void GameButton::enterEvent(QEnterEvent *event) {
    up();
}

void GameButton::leaveEvent(QEvent *event) {
    down();
}

void GameButton::up()
{
    QVariantAnimation *animation = new QVariantAnimation(this);
    animation->setStartValue(offset_);
    animation->setEndValue(shadow_offset_);
    animation->setDuration(150);
    connect(animation, &QVariantAnimation::valueChanged, this, [this](const QVariant &value) {
        offset_ = value.toInt();
        update();
    });
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void GameButton::down()
{
    QVariantAnimation *animation = new QVariantAnimation(this);
    animation->setStartValue(offset_);
    animation->setEndValue(0);
    animation->setDuration(150);
    connect(animation, &QVariantAnimation::valueChanged, this, [this](const QVariant &value) {
        offset_ = value.toInt();
        update();
    });
    animation->start(QAbstractAnimation::DeleteWhenStopped);
}

